//
//  HJSVGView.m
//  KaiChat
//
//  Created by lx on 2023/11/1.
//

#import "HJSvgaAnimationView.h"
#import <SVGAPlayer/SVGAPlayer.h>
#import <SVGAParser.h>

@interface HJSvgaAnimationView()<SVGAPlayerDelegate>

@property (nonatomic, strong) SVGAPlayer *svgaPlayer;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, weak) UIImageView *imageView;
@property (nonatomic, strong) SVGAVideoEntity *videoItem;

@end


@implementation HJSvgaAnimationView


- (HJSvgaAnimationView *)initWithName:(NSString *)name {
    if (self = [self initWithFrame:CGRectZero]) {
        self.name = name;
    }
    return self;
}

 
- (SVGAPlayer *)svgaPlayer {
    if (!_svgaPlayer) {
        _svgaPlayer = [[SVGAPlayer alloc] init];
        _svgaPlayer.delegate = self;
        _svgaPlayer.loops = 1;
        _svgaPlayer.clearsAfterStop = NO;
    }
    return _svgaPlayer;
}
 
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        UIImageView *imageView = [UIImageView addToView:self];
        _imageView = imageView;
        
        [self addSubview:self.svgaPlayer];
    }
    return self;
}

  
- (void)play {
    
    if (!_svgaPlayer) {
        [self addSubview:self.svgaPlayer];
        self.svgaPlayer.frame = self.bounds;
    }
    
    
    TJWeakify(self)
    SVGAParser *parser = [[SVGAParser alloc] init];
    [parser parseWithURL:[[NSBundle mainBundle] URLForResource:self.name withExtension:nil] completionBlock:^(SVGAVideoEntity * _Nullable videoItem) {
        if (videoItem) {
            weakself.imageView.hidden = YES;
             weakself.svgaPlayer.videoItem = videoItem;
             [weakself.svgaPlayer startAnimation];
         }
    } failureBlock:nil];
 
}

- (void)svgaPlayerDidFinishedAnimation:(SVGAPlayer *)player {
    self.imageView.hidden = NO;
    self.imageView.image = [HJTools convertViewToImage:player];;
    [self.svgaPlayer removeFromSuperview];
    [self.svgaPlayer stopAnimation];
    self.svgaPlayer = nil;
}
 
- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.imageView.frame = self.bounds;
    self.svgaPlayer.frame = self.bounds;
}


@end
